#include"definicoes.h"

boolean localiza(int id, FILE *fp){
  char lixo;
  int i,idAux,j=1;
  if (id<0) return no;
  fseek(fp, 0, SEEK_SET);
  if((fscanf(fp,"%d",&idAux))<1) return no;
  while(id!=idAux){
    do {
      lixo=fgetc(fp);
    } while(lixo!='\n');
    if((fscanf(fp,"%d",&idAux))<1) return no;
  }
  for(i=id;i/10>0;i=i/10) j++;
  fseek(fp,(-1)*j,SEEK_CUR);
  return yes;
}

int compara_data(int data1, int data2){
	int num[8], i, dia1, mes1, ano1, dia2, mes2, ano2;
	for(i=7; i>=0; i--){
		num[i] = data1%10;
		data1 -= num[i];
		data1 = data1/10;
	}
	dia1 = num[0]*10+num[1];
	mes1 = num[2]*10+num[3];
	ano1 = num[4]*1000+num[5]*100+num[6]*10+num[7];

	for(i=7; i>=0; i--){
		num[i] = data2%10;
		data2 -= num[i];
		data2 = data2/10;
	}
	dia2 = num[0]*10+num[1];
	mes2 = num[2]*10+num[3];
	ano2 = num[4]*1000+num[5]*100+num[6]*10+num[7];

	if(ano1 > ano2) return 1;
	if(ano1 < ano2) return -1;
	if(mes1 > mes2) return 1;
	if(mes1 < mes2) return -1;
	if(dia1 > dia2) return 1;
	if(dia1 < dia2) return -1;
	return 0;
}

void ler_frase_arq(char * field, int tamanho, FILE * arq){
	int i;
	char ch1, ch2;
	for(i=0; i<tamanho-1; i++){
		ch1 = fgetc(arq);
		if(ch1 == '\n'){
			field[i] = '\0';
			return;
		}
		else if(ch1 == ' '){
			ch2 = fgetc(arq);
			if(ch2 == '#'){
				field[i] = '\0';
				return;
			}
			else{
				field[i] = ch1;
				field[i+1] = ch2;
				i++;
			}
		}
		else{
			field[i] = ch1;
		}
	}
	return;
}


void criaLista(list * lista){
	lista->id = -1;
	lista->offset = 0;
	lista->prox = NULL;
}

void criaIndSec(ind_sec * ind){
	ind->indice = -1;
	ind->lista = (list *) malloc (sizeof(list));
	criaLista(ind->lista);
	ind->prox = NULL;
}

ind_sec * busca_esp(int id_esp){
	ind_sec * ind_aux;
	for(ind_aux = ind_sec_ind;
		ind_aux != NULL && ind_aux->indice != id_esp;
		ind_aux = ind_aux->prox); /*Percorre o indice secundario buscando aquele id de especie ja existente*/
	return (ind_aux);
}

ind_sec * busca_ind(int id_ind){
	ind_sec * ind_aux;
	for(ind_aux = ind_sec_cap;
		ind_aux != NULL && ind_aux->indice != id_ind;
		ind_aux = ind_aux->prox); /*Percorre o indice secundario buscando aquele id de individuo ja existente*/
	return (ind_aux);
}

void ler_string(char * field, FILE * fr){
	int i;
	char ch;
	for(i=0; ;i++){
		ch = fgetc(fr);
		if(ch == '\n' || ch == '|'){
			field[i] = '\0';
			return;
		}
		else field[i] = ch;
	}
	return;
}

boolean ler_capturas(FILE * arq, captura * capt){
	int dados[5];
	char local[50];
	if(fread(dados, sizeof(int), 5, arq)<1) return no;
	fread(local, sizeof(char), 50, arq);
	capt->id = dados[0];
	capt->comp = dados[1];
	capt->larg = dados[2];
	capt->peso = dados[3];
	capt->data = dados[4];
	strcpy(capt->local, local);
	return yes;
}